import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  ListView,
  Image,
  Switch,
  Dimensions,
  Text,
  TouchableOpacity,
  ScrollView,
  PanResponder,
} from 'react-native'
import NavigationBar from '../../components/common/NavigationBar'
import IconModel from '../../components/common/IconModel'
import { BoxShadow } from 'react-native-shadow'
import { MtContainer, MtChar,  MtNavBar, MtScreen } from 'martian-ui';
import { bindActionCreators } from 'redux';
import assign from 'lodash/assign';
import {connect} from 'react-redux';
const EntityLabels = require('../../constants/entities');
const { width, height } = Dimensions.get('window')
const HALF_WIDTH = 128;
let _previousLeft = 0;
import {fetchDeviceDetailById, controlDevice } from '../../action/girlAction';
let lastLeft = 0;

class ClothCurtain extends Component {
  constructor(props) {
    super(props);

    this.state = {
      iconModelList: [
        {
          id: 0,
          icon: 'icon_chuanglian_guan',
          name: '关窗帘',
          color: '#676767'

        },
        {
          id:1,
          icon: 'icon_chuanglian_kai',
          name: '开窗帘',
          color: '#669CE5',
        },
        {
          id: 2,
          icon: 'icon_chuanglian_stop',
          name: '暂停',
          color: '#F2736D'
        }
      ],
      switchValue: false,
      openDegree: 0,
      openDegreeStyle: {
        width:  0,
      },
      btnStyle: {marginLeft:  0,},
    };
    this.dataSource = new ListView.DataSource({
      rowHasChanged: ((row1, row2) => row1 !== row2)
    });
    this.onStartShouldSetPanResponder = this.onStartShouldSetPanResponder.bind(this);
    this.onMoveShouldSetPanResponder = this.onMoveShouldSetPanResponder.bind(this);
    this.onPanResponderGrant = this.onPanResponderGrant.bind(this);
    this.onPanResponderMove = this.onPanResponderMove.bind(this);
    this.onPanResponderRelease = this.onPanResponderRelease.bind(this);
  }

  convertPropsToStates(props) {
    const {devicesEntities, deviceId} = props;
    const device = devicesEntities[deviceId];
    if(device && device.status && device.status.curtainPosition) {
      const showWidth = device.status.curtainPosition && (parseInt(device.status.curtainPosition, 10) *  HALF_WIDTH /100);

      this.setState({
        openDegreeStyle: {
          width: showWidth,
      },
        openDegree: device.status.curtainPosition,

        btnStyle: {marginLeft: showWidth},})

    }
    const newState = assign({
      device
    });

    if (newState) {
      this.setState(newState);
    }
  }

  componentWillReceiveProps(nextProps) {
    this.convertPropsToStates((nextProps));
  }


  componentWillMount(evt, gestureState) {

    this.convertPropsToStates(this.props);
    this._panResponder = PanResponder.create({
      //用户开始触摸屏幕的时候，是否愿意成为响应者；默认返回false，无法响应，
      // 当返回true的时候则可以进行之后的事件传递。
      onStartShouldSetPanResponder: this.onStartShouldSetPanResponder,

      //在每一个触摸点开始移动的时候，再询问一次是否响应触摸交互；
      onMoveShouldSetPanResponder: this.onMoveShouldSetPanResponder,

      //开始手势操作，也可以说按下去。给用户一些视觉反馈，让他们知道发生了什么事情！（如：可以修改颜色）
      onPanResponderGrant: this.onPanResponderGrant,

      //最近一次的移动距离.如:(获取x轴y轴方向的移动距离 gestureState.dx,gestureState.dy)
      onPanResponderMove: this.onPanResponderMove,

      //用户放开了所有的触摸点，且此时视图已经成为了响应者。
      onPanResponderRelease: this.onPanResponderRelease,

      //另一个组件已经成为了新的响应者，所以当前手势将被取消。
      onPanResponderTerminate: this.onPanResponderEnd,
    });
  }
  //用户开始触摸屏幕的时候，是否愿意成为响应者；
  onStartShouldSetPanResponder(evt, gestureState) {
    return true;
  }

  //在每一个触摸点开始移动的时候，再询问一次是否响应触摸交互；
  onMoveShouldSetPanResponder(evt, gestureState) {
    return true;
  }

  // 开始手势操作。给用户一些视觉反馈，让他们知道发生了什么事情！
  onPanResponderGrant(evt, gestureState) {
    console.log(parseInt(_previousLeft/HALF_WIDTH));
  }
  controlAir(params){
    const {controlDevice, deviceId} = this.props;
    controlDevice(params, deviceId);
  }
  componentDidMount() {
    const { fetchDeviceDetailById,  deviceId} = this.props;
    fetchDeviceDetailById(deviceId);
  }

  // 最近一次的移动距离为gestureState.move{X,Y}
  onPanResponderMove(evt, gestureState) {

    _previousLeft = lastLeft + gestureState.dx;

    //主要是限制小球拖拽移动的时候不许出屏幕外部
    if (_previousLeft <= 0) {
      _previousLeft = 0
    }

    if (_previousLeft >= HALF_WIDTH) {
      _previousLeft = HALF_WIDTH
    }


    //实时更新
    this.setState({
      openDegreeStyle: {
        width:  _previousLeft
      },
      btnStyle: {
        marginLeft: _previousLeft,
      },
      openDegree: parseInt(_previousLeft/HALF_WIDTH*100)
    });
  }

  // 用户放开了所有的触摸点，且此时视图已经成为了响应者。
  // 一般来说这意味着一个手势操作已经成功完成。
  onPanResponderRelease(evt, gestureState) {
    this.controlAir({CurtainPosition: this.state.openDegree})
    lastLeft = _previousLeft
  }
  render() {
    const {device} = this.state;
    const status = device && device.status;
    return (
      <MtContainer>
        <View style={styles.container}>
          <NavigationBar
            title={'布帘'}
            statusBar={{backgroundColor: '#F4F4F4', barStyle: 'dark-content'}}
            style={{backgroundColor: '#F4F4F4'}}
            navigator={this.props.navigator}
          />
          <ScrollView contentContainerStyle={styles.contentContainer} showsVerticalScrollIndicator={false}>
            <View>
              <Text style={styles.title}>开合度</Text>
              <View style={styles.svgView}>
                <View style={styles.titleView}></View>
                <View style={styles.bottomView}>
                  <View style={styles.bgView}>
                    <View style={[styles.openContent, this.state.openDegreeStyle]}></View>
                    <View style={[styles.openContent, this.state.openDegreeStyle]}></View>
                  </View>
                  <View style={styles.btnView}>
                    <View style={[styles.btn, this.state.btnStyle]} {...this._panResponder.panHandlers}>
                      <TouchableOpacity>
                        <Image style={{width: 42, height: 42,}} source={require('../../img/btn_33.png')}/>
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              </View>
              <Text style={styles.svgValue}>{ this.state.openDegree}%</Text>
            </View>
            <View style={[styles.operation, styles.flex]}>
              {this._renderList(this.state.iconModelList)}
            </View>
            <View style={styles.modelList}>
              <BoxShadow setting={this._getShadowOpt({
                width: width - 30,
                height: 94,
                style: {marginTop: 10}
              })}>
                <View style={styles.power}>
                  <View style={styles.flex}>
                    <Text style={styles.powerText}>指令反向</Text>
                    <Switch
                      style={styles.powerSwitch}
                      value={this.state.switchValue}
                      onTintColor='#00A5AD'
                      onValueChange={
                        (value)=>{
                          this.setState({
                            switchValue:value
                          })
                        }
                      }
                    />
                  </View>
                  <Text style={styles.info}>开启此选项后，场景模式指令将会按反向状态</Text>
                </View>
              </BoxShadow>
            </View>
          </ScrollView>
        </View>
      </MtContainer>
    )
  }
  _renderList(list) {
    return list.map( item => this._renderItem(item) );
  }
  _onModelPressButton(rowData) {
    console.warn(2222)
    console.warn(JSON.stringify(rowData))
    this.controlAir({CurtainOperation: rowData.id})

  }
  _renderItem(item) {
    return (

        <IconModel
          handlePress={
            this._onModelPressButton.bind(this, item)
          }

          width={100}
          height={100}
          fontSize={13}
          iconSize={48}
          icon={item.icon}
          name={item.name}
          color={item.color}
        />
    )
  }
  _getShadowOpt(data) {
    return {
      width: data.width,
      height: data.height,
      color: "#999999",
      border: 2,
      radius: 6,
      opacity: 0.1,
      x: 0,
      y: 2,
      style: data.style
    }
  }
}

const styles = StyleSheet.create({
  container: {

  },
  contentContainer: {
    marginBottom: 20,
  },
  title: {
    color: '#333333',
    fontSize: 14,
    marginTop: 15,
    marginLeft: 35,
    fontWeight: 'bold',
  },
  svgView: {
    paddingTop: 21,
    paddingBottom: 21,
    alignItems: 'center',
  },
  titleView: {
    width: 290,
    height: 22,
    borderRadius: 11,
    backgroundColor: '#06939A',
  },
  bgView: {
    width: 256,
    height: 240,
    flexDirection: 'row',
    backgroundColor: '#00A5AD',
    justifyContent: 'center',
    alignItems: 'center',
  },
  openContent: {
    height: 240,
    backgroundColor: '#ffffff',
  },
  btnView: {
    position: 'absolute',
    right: 0,
    height: 42,
    width: 167,
  },
  btn: {
    width: 42,
    height: 42,
    transform: [{rotate: '90deg'}]
  },
  bottomView: {
    width: 290,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
  },
  svgValue: {
    textAlign: 'center',
    fontSize: 24,
    color: '#666666',
    marginBottom: 20,
  },
  operation: {
    width: width - 30,
    marginLeft: 15
  },
  modelList: {
    marginBottom: 30,
    marginLeft: 15
  },
  flex: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  power: {
    height: 94,
    width: width - 30,
    backgroundColor: '#fff',
    borderRadius: 6,
    paddingLeft: 20,
    paddingRight: 20,
    justifyContent: 'center',
  },
  powerText: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#333333',
  },
  powerSwitch: {
  },
  info: {
    color: '#666666',
    fontSize: 13,
    marginTop: 14,
  }
})

function mapDispatchToProps(dispatch) {
  const actions = {
    fetchDeviceDetailById,
    controlDevice
  };
  return bindActionCreators(actions, dispatch);
}

function mappingStateToProps(state, ownProps) {
  const entities= state['entities'];
  const devicesEntities = entities[EntityLabels.devices];

  return {
    devicesEntities,
  }
}

module.exports = connect(mappingStateToProps, mapDispatchToProps)(ClothCurtain);

